package com.maikobi.maikobi.config.handler;


import com.maikobi.maikobi.mapper.ChartMapper;
import com.maikobi.maikobi.model.entity.Chart;
import com.maikobi.maikobi.task.ChartGenerateTask;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

// 自动为所有 final 字段生成带参构造函数。

/**
 * @RequiredArgsConstructor 自动为所有 final 字段生成带参构造函数。
 * 等价于你手写了下面这个构造函数：
 * public ChartRejectedExecutionHandler(ChartMapper chartMapper) {
 *     this.chartMapper = chartMapper;
 * }
 */
//@RequiredArgsConstructor
@Slf4j
public class DatabaseRejectedExecutionHandler implements RejectedExecutionHandler {

    private final ChartMapper chartMapper;
    public DatabaseRejectedExecutionHandler(ChartMapper chartMapper) {
        this.chartMapper = chartMapper;
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        if (r instanceof ChartGenerateTask) {
            ChartGenerateTask task = (ChartGenerateTask) r;
            Chart originChart = task.getChart();

            Chart chart = new Chart();
            chart.setChartName("延迟执行-" + originChart.getChartName());
            chart.setGoal(originChart.getGoal());
            chart.setChartData(originChart.getChartData());
            chart.setChartType(originChart.getChartType());
            chart.setUserId(originChart.getUserId());
            chart.setStatus(0); // 等待执行
            chart.setExecMessage("线程池繁忙，任务被转为延迟执行");
            chart.setIsDelete(0);

            int rows = chartMapper.insert(chart);
            if (rows > 0) {
                log.warn("线程池已满，图表任务转存数据库，chartId = {}", chart.getId());
            } else {
                log.error("线程池已满，图表任务转存数据库失败，chartName = {}", chart.getChartName());
            }
        } else {
            log.warn("拒绝执行的任务不是 ChartGenerateTask 类型，忽略。任务类型：{}", r.getClass().getName());
        }
    }
}


